/*****************************************************************************/ /*!
* file  : systask.c
* creat : apleilx
* note :  除初始化外，禁止该任务及其子程序使用含有阻塞的功能，包括数据存储，USB操作等等
* data  : 2019/07/02
*******************************************************************************/
#include "bsp.h"
#include "os_obj.h"
#include "sys_task.h"
#include "common.h"

#include "bsp_api.h"
#include "bsp_spi_nor.h"
#include "nor_cmd.h"

#include "lut\nand_lut.h"
#include "nand_w25n.h"

#include "simp_fat.h"

#include "fat_opt.h"

extern nand_lut_type nand_dev;

/*****************************************************************************
* @brief   const define
*****************************************************************************/
#define NAND_BLOCK_SITE_FILE 16
#define SIMP_TAB_ADDR_BASE	0x400000

/*****************************************************************************
* @brief   simp_fat hal layer
* @param   none
* @return  non
*****************************************************************************/
simp_fat_err simp_fat_t_read(void *buff, int32_t addr, int32_t len)
{
	nor_read(addr + SIMP_TAB_ADDR_BASE, len, buff);

	return SIMP_FAT_OK;
}

simp_fat_err simp_fat_dat_read(void *buff, int32_t addr, int32_t len)
{
	addr += NAND_BLOCK_SITE_FILE * nand_dev.page_main_size * nand_dev.page_per_block;
	//nand_dev.api.addr_read(addr, len, buff);

	nand_lut_addr_read(&nand_dev, addr, len, buff);
	
	return SIMP_FAT_OK;
}

/*****************************************************************************
* @brief   simp_fat_test
* @param   none
* @return  non
*****************************************************************************/
uint8_t simp_fat_file_read(void)
{
	simp_fat_type sfat;
	simp_fat_fil_type sfil;
	simp_fat_err serr;
	int32_t len_back;

	if (!sfat_opt.simp_fat_req && !sys_st.cmd.fread_req)
	{
		return 1;
	}

	if (sfat_opt.simp_fat_req)
	{
		copy_str("tx_user.h", sys_st.cmd.fil_name, sizeof(sys_st.cmd.fil_name));
	}

	nand_dev.api.read_init();

	// clear flag
	sfat_opt.simp_fat_req = 0;
	sys_st.cmd.fread_req = 0;

	// init fat
	serr = simp_fat_init(&sfat, (void*)simp_fat_t_read, (void*)simp_fat_dat_read, 1);

	if (serr)
	{
		dbg_print("simp fat init err: %d \n", serr);
		return serr;
	}

	// open file
	serr = simp_fat_open(&sfat, &sfil, sys_st.cmd.fil_name);

	if (serr)
	{
		dbg_print("simp fat open %s err: %d \n", sys_st.cmd.fil_name, serr);
		return serr;
	}

	flash_dbg_print("simp open sucess: addr =%08X size=%08X \n", sfil.info.addr_base, sfil.info.size);

	// read file data
	sfat_opt.buff = malloc(1024);
	do
	{
		memset(sfat_opt.buff,0, 401);
		serr = simp_fat_read(&sfil, sfat_opt.buff, 400, &len_back);

		if (serr)
		{
			dbg_print("simp fat read file %s err: %d \n", sys_st.cmd.fil_name, serr);
			return serr;
		}

		((char *)(sfat_opt.buff))[len_back] = 0;

		dbg_puts((char *)sfat_opt.buff);

	} while (len_back == 400);

	// close file
	serr = simp_fat_close(&sfil);

	free(sfat_opt.buff);
	
	return serr;
}
